import json
from utils.progress_bar import index
from channels.channels import Channel


class ReadJson2Lines(Channel):
    required = ['file_path']
    send = ['lines']
    
    @staticmethod
    def execute(args={}, meta={}, lines=[], **kwargs):

        new_lines= []
        file_path = args.get('file_path', '')
        key_word = kwargs.get('json_key_word', '')

        with open(file_path, 'r', encoding='utf-8') as fr:
            lines = fr.readlines()

            for index, line in enumerate(lines):
                line = line.strip()
                line_obj = json.loads(line)
                line = line_obj.get(key_word, '')
                if line:
                    new_lines.append(line)                
            
                # bar show
                args.bar_show(index, len(lines))

            if new_lines:
                raise KeyError('No this key word: ', key_word)
            return {
                'lines': lines
            }